<?php
require_once("lib.php");
require_once('data.php');

$js = json_decode($_POST['js'], true);
if($js === NULL) die();

$cart = &get_cart();
$user = &get_user();

$rjs = array('errno' => 0, 'errs'=>'');

if(!$cart['id']) {
    $rjs['errno'] = -2;
    $rjs['errs'] = 'Empty Cart!';
    die( json_encode($rjs) );
}

$js['acct_id'] = strtolower($js['acct_id']);

$dbc = dbc();

if(!$user['user_id'] && $js['acct_id']) {
    $res = $dbc->query(sprintf("select count(*) from user where user_acct='%s' and user_flg&1!=0",
        $dbc->escape_string($js['acct_id'])
        )
    );
    if($res && ($row=$res->fetch_row()) && intval($row[0])) {
        $rjs['errno'] = -1;
        $rjs['errs'] = 'The Email Or Phone Number Already Exists!';
        die( json_encode($rjs) );
    }
    
}

validate_cart();
$cart_total = get_cart_total();

$order_info = $js['order_info'];
$card_info = $js['card_info'];


$user['js']['order_info'] = $order_info;
$user['js']['card_info'] = $card_info;

$user_id = $user['user_id'];
if($user_id) {
    set_user($user);
} elseif($js['acct_id']) {
    $user_id = new_user( array('acct_id'=>$js['acct_id'], 'acct_passwd'=>$js['acct_passwd'], 'js'=>$user['js']) );
}
if($user_id < 0) $user_id = 0;

$order_js = array(
    'order_info' => $order_info,
    'card_info' => $card_info,
    'total' => $cart_total,
    'items' => $cart['lst']
);

$dbc->query(sprintf("insert into uorder values(null,%s,0,%d,%d,'%s')",
    time(), $cart['id'], $user_id, $dbc->escape_string(json_encode($order_js))
    )
);

$dbc->query(sprintf('update cart set flg=flg|1 where id=%d', $cart['id']));



?>